package com.fckbug.action.user;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.fckbug.service.UserService;
import com.fckbug.util.SpringContextHolder;
import com.mysql.jdbc.StringUtils;


/**
 * @struts.action path="/register.do"
 * @struts.action-forward name="result" path=""
 */
public class RegisterAction extends Action {
	UserService userService = (UserService)SpringContextHolder.getBean("userService");
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	            HttpServletRequest request, HttpServletResponse response) throws Exception {
		String nickname = request.getParameter("nickname");
		String username = request.getParameter("username");
		String loginpass = request.getParameter("loginpass");
		String verifypass = request.getParameter("verifypass");
		String verifycode = request.getParameter("verifycode");
		String rand = (String)request.getSession().getAttribute("rand");//服务器保存的随机数
		
		request.setAttribute("code", "0");//reg fail
		if(StringUtils.isNullOrEmpty(nickname) ||StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(loginpass) 
				|| StringUtils.isNullOrEmpty(verifypass) || StringUtils.isNullOrEmpty(verifycode)) {
			request.setAttribute("detail", "不能为空");
		} else {
			try {
				if(!loginpass.equals(verifypass)) {
					request.setAttribute("detail", "确认密码不一致");
				} else if(!rand.equals(verifycode)){
					request.setAttribute("detail", "校验码有误");
				} else {
					List list = userService.getUserByUsername(username);
					if(list.size()>0) {
						request.setAttribute("detail", "用户名已存在");
					} else {
						if(userService.saveRegUser(username, loginpass, nickname)) {//reg success
							request.setAttribute("code", "1");//1
							request.setAttribute("detail", "注册成功");
						}
					}
				}
			} catch(Exception ex) {
				request.setAttribute("detail", "系统异常");
				ex.printStackTrace();
			}
		}
		return mapping.findForward("result");
	}
}

